package so.shanku.essential.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
import aym.util.getservicesdata.GetServicesDataQueue;
import aym.util.getservicesdata.GetServicesDataUtil;
import aym.util.json.JsonMap;
import aym.util.json.JsonParseHelper;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import so.shanku.essential.R;
import so.shanku.essential.activity.FindDetailActivity;
import so.shanku.essential.activity.FindSearchActivity;
import so.shanku.essential.adapter.FindProductAdapter;
import so.shanku.essential.adapter.MenuAdapter;
import so.shanku.essential.app.MyApplication;
import so.shanku.essential.getdata.GetDataConfing;
import so.shanku.essential.getdata.GetDataQueue;
import so.shanku.essential.getdata.JsonKeys;
import so.shanku.essential.getdata.ShowGetDataError;
import so.shanku.essential.utils.Constant;
import striveen.util.used.view.view.XListView;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by Jaelyn on 2015/9/6 0006.
 * 页面需要获取屏幕的宽高
 */
public class FindProductFragment extends BaseFragment {

    @ViewInject(R.id.find_page_lv)
    private XListView xListView;
    @ViewInject(R.id.nodata_layout) //无数据
    private LinearLayout nodataLayout;

    @ViewInject(R.id.main_top_layout) //title
    private LinearLayout main_top_layout;
    @ViewInject(R.id.theme1_layout) //title
    private LinearLayout theme1_layout;
    @ViewInject(R.id.theme2_layout) //title
    private RelativeLayout theme2_layout;
    @ViewInject(R.id.theme1_tv)
    private TextView theme1_tv;
    @ViewInject(R.id.theme2_tv)
    private TextView theme2_tv;
    @ViewInject(R.id.iv_search)
    private ImageView iv_search;

    private int pageSize = 10;
    private int currentPage = 0;
    /**
     * 信息数据
     */
    private ArrayList<JsonMap<String, Object>> dataList = new ArrayList<JsonMap<String, Object>>();
    private FindProductAdapter findAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.findproduct_fragment_layout, container, false);
        initCompont(view);
        theme1_tv.setText(R.string.source);
        theme2_tv.setText(R.string.sort);
        sortData = new ArrayList<JsonMap<String, Object>>();

        JsonMap jsonMap = new JsonMap();
        jsonMap.put("sortId", 0);
        jsonMap.put("title", getString(R.string.lastest));
        sortData.add(jsonMap);

        JsonMap hotJsonMap = new JsonMap();
        hotJsonMap.put("sortId", 1);
        hotJsonMap.put("title", getString(R.string.hot));
        sortData.add(hotJsonMap);

        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        findAdapter = new FindProductAdapter(activity);
        //findAdapter.setItemClickListener(goodsPicItemClickListener);
        xListView.setAdapter(findAdapter);
        xListView.setPullRefreshEnable(true);
        xListView.setPullLoadEnable(true);
        xListView.setXListViewListener(loadMoreListener);
        xListView.setOnItemClickListener(onItemClickListener );
        loadingToast.show();
        getServerData(0);
    }

    /**
     * item  点击监听
     */
    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int itemPosition, long id) {
            JsonMap jsonMap_temp = (JsonMap) dataList.get(itemPosition - 1);
            String discoreId = jsonMap_temp.getStringNoNull("Id");
            Intent intent = new Intent(activity, FindDetailActivity.class);
            intent.putExtra(Constant.ID, discoreId);
            intent.putExtra(Constant.NAME, jsonMap_temp.getStringNoNull("Title"));
            activity.jumpTo(intent, false);
        }
    };

    private XListView.IXListViewListener loadMoreListener = new XListView.IXListViewListener() {
        @Override
        public void onRefresh() {
            currentPage = 0;
            getServerData(1);
        }

        @Override
        public void onLoadMore() {
            getServerData(2);
        }
    };

    /**
     * 获取服务器端数据
     *
     * @param requestType 请求类型
     */
    public void getServerData(int requestType) {
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);
        params.put("currentPage", currentPage + 1);
        params.put("pageSize", pageSize);

        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.Action_GetDiscover);
        queue.setTag(requestType);
        queue.setParamsNoJson(params);
        queue.setCallBack(callBack);
        queue.setWhat(GetDataConfing.What_GetDiscover);
        getDataUtil.getData(queue);
    }


    private GetServicesDataUtil.IGetServicesDataCallBack callBack = new GetServicesDataUtil.IGetServicesDataCallBack() {

        @Override
        public void onLoaded(GetServicesDataQueue entity) {
            xListView.stopLoadMore();
            xListView.stopRefresh();
            if (entity.isOk()) {
                if (ShowGetDataError.isCodeSuccess(activity, entity.getInfo())) {
                    if (entity.what == GetDataConfing.What_GetDiscover) {
                        ArrayList<JsonMap<String, Object>> temp_data = (ArrayList<JsonMap<String, Object>>) JsonParseHelper.getJsonMap_List_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                        setAdapterData(temp_data, (Integer) entity.getTag());
                        validateData();
                    }
                }
            } else {
                ShowGetDataError.showNetError(activity);
            }
            loadingToast.dismiss();
        }

    };

    /**
     * 校验数据 显示无数据等
     * 是否请求正常 网络错误且数据为空的话显示网络异常界面 提供刷新的接口
     *
     * @param
     */
    private void validateData() {
        if (dataList == null || dataList.size() == 0) {
            xListView.setVisibility(View.GONE);
            nodataLayout.setVisibility(View.VISIBLE);
        } else {
            xListView.setVisibility(View.VISIBLE);
            nodataLayout.setVisibility(View.GONE);
        }
    }

    private void setAdapterData(ArrayList<JsonMap<String, Object>> temp_data, int requestType) {
        if (temp_data.size() == 0) {
            xListView.setPullLoadEnable(false);
        } else {
            xListView.setPullLoadEnable(true);
        }
        if (requestType == 0 || requestType == 1) {
            dataList.addAll(0, temp_data);
        } else {
            dataList.addAll(temp_data);
        }
        findAdapter.setDatas(dataList);
        findAdapter.notifyDataSetChanged();
    }


    private void initCompont(View view) {
        ViewUtils.inject(this, view);
    }


    private PopupWindow mSourceListPop;
    private ArrayList<JsonMap<String, Object>> sourceData;
    private boolean isOutTouch = false;

    /**
     * 来源
     *
     * @param view
     */
    @OnClick(R.id.theme1_tv)
    public void theme1_tv_click(View view) {
        if (mListPop != null && mListPop.isShowing()) {
            mListPop.dismiss();
        }
        isSortOutTouch = false;
        if (mSourceListPop != null && mSourceListPop.isShowing()) {
            mSourceListPop.dismiss();
            return;
        }
        if (isOutTouch) {
            isOutTouch = false;
            return;
        }
        ListView listView = new ListView(activity);
        listView.setDivider(activity.getResources().getDrawable(R.drawable.hor_line));
        int pad = getResources().getDimensionPixelSize(R.dimen.common_margin);
        listView.setPadding(pad, 0, pad, 0);
        MenuAdapter menuAdapter = new MenuAdapter(activity, sortData);
        listView.setAdapter(menuAdapter);
        //window.setFocusable(true);//如果不设置setFocusable为true，popupwindow里面是获取不到焦点的，那么如果popupwindow里面有输入框等的话就无法输入。
        mSourceListPop = new PopupWindow(listView, MyApplication.getInstance().getScreenWidth() / 2, ViewGroup.LayoutParams.WRAP_CONTENT);
        mSourceListPop.setBackgroundDrawable(getResources().getDrawable(R.drawable.cus_grey_border_frame));
        mSourceListPop.setOutsideTouchable(true);
        mSourceListPop.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    mSourceListPop.dismiss();
                    isOutTouch = true;
                }
                return false;
            }
        });

        mSourceListPop.showAsDropDown(theme1_layout);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                theme2_tv.setText(sortData.get(position).getStringNoNull("title"));
                mSourceListPop.dismiss();
            }
        });
    }


    private PopupWindow mListPop;
    private ArrayList<JsonMap<String, Object>> sortData;
    private boolean isSortOutTouch = false;

    /**
     * 排序
     *
     * @param view
     */
    @OnClick(R.id.theme2_tv)
    public void theme2_tv_click(View view) {
        if (mSourceListPop != null && mSourceListPop.isShowing()) {
            mSourceListPop.dismiss();
        }
        isOutTouch = false;
        if (mListPop != null && mListPop.isShowing()) {
            mListPop.dismiss();
            return;
        }

        if (isSortOutTouch) {
            isSortOutTouch = false;
            return;
        }
        ListView listView = new ListView(activity);
        listView.setDivider(activity.getResources().getDrawable(R.drawable.hor_line));
        int pad = getResources().getDimensionPixelSize(R.dimen.common_margin);
        listView.setPadding(pad, 0, pad, 0);
        MenuAdapter menuAdapter = new MenuAdapter(activity, sortData);
        listView.setAdapter(menuAdapter);
        mListPop = new PopupWindow(listView, MyApplication.getInstance().getScreenWidth() / 2, ViewGroup.LayoutParams.WRAP_CONTENT);
        mListPop.setBackgroundDrawable(getResources().getDrawable(R.drawable.cus_grey_border_frame));
        mListPop.setOutsideTouchable(true);
        mListPop.setSplitTouchEnabled(false);
        mListPop.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    mListPop.dismiss();
                    isSortOutTouch = true;
                }
                return false;
            }
        });
        mListPop.showAsDropDown(theme2_layout);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                theme2_tv.setText(sortData.get(position).getStringNoNull("title"));
                mListPop.dismiss();
            }
        });
    }


    /**
     * 搜索图标
     *
     * @param view
     */
    @OnClick(R.id.iv_search)
    public void iv_search_click(View view) {
        Intent findSearchIntent = new Intent(activity, FindSearchActivity.class);
        activity.jumpTo(findSearchIntent, false);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (mListPop != null && mListPop.isShowing()) {
            mListPop.dismiss();
        }

        if (mSourceListPop != null && mSourceListPop.isShowing()) {
            mSourceListPop.dismiss();

        }

        isOutTouch = false;
        isSortOutTouch = false;
    }

    /**
     * back 键处理
     * @return   true：消费此次返回  false  不处理
     */
    public boolean backKeyClick(){
        isOutTouch = false;
        isSortOutTouch = false;
        if (mListPop != null && mListPop.isShowing()) {
            mListPop.dismiss();
            return true;
        }

        if (mSourceListPop != null && mSourceListPop.isShowing()) {
            mSourceListPop.dismiss();
            return true;
        }
        return false;
    }
}